/**
 * Copyright 2025 Beijing Volcano Engine Technology Co., Ltd. All Rights Reserved.
 * SPDX-license-identifier: BSD-3-Clause
 */

import { useState, useEffect } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { message } from 'antd';
import AvatarCard from '@/components/AvatarCard';
import Utils from '@/utils/utils';
import InvokeButton from '@/pages/MainPage/MainArea/Antechamber/InvokeButton';
import { useJoin } from '@/lib/useCommon';
import { useAuth } from '@/app/auth';
import LoginModal from '@/components/LoginModal';
import { getChatHistory, createChatHistory } from '@/services/chatHistory';
import { RootState } from '@/store';
import { updateCurrentChat } from '@/store/slices/room';
import { sidebarEvents } from '@/store/hooks/useSidebar';
import style from './index.module.less';
import AntechamberConversation from './AntechamberConversation';

function Antechamber() {
  const [joining, dispatchJoin] = useJoin();
  const [loginVisible, setLoginVisible] = useState(false);
  const [loading, setLoading] = useState(false);
  const { isAuthenticated, user, refreshUserInfo } = useAuth();
  const dispatch = useDispatch();
  const currentChatHistoryId = useSelector((state: RootState) => state.room.chatHistory?.id);

  // 获取当前聊天历史的房间ID
  const roomId = useSelector((state: RootState) => state.room.chatHistory?.roomId);

  // 使用用户名或默认ID
  const username = isAuthenticated && user?.username ? user.username : '';

  // 获取用户的聊天历史
  const fetchChatHistory = async () => {
    if (!isAuthenticated) return;

    try {
      const historyList = await getChatHistory();
      if (historyList && historyList.length > 0) {
        // 使用最新的一条聊天历史
        dispatch(updateCurrentChat(historyList[0]));
        console.log('已获取现有聊天历史ID:', historyList[0]);
      } else {
        dispatch(updateCurrentChat(null));
        console.log('没有找到现有的聊天历史');
      }
    } catch (error) {
      console.error('获取聊天历史失败:', error);
      message.error('获取聊天历史失败');
    }
  };

  // 加载用户的聊天历史
  useEffect(() => {
    if (isAuthenticated && currentChatHistoryId === null) {
      fetchChatHistory();
    }
  }, [isAuthenticated]);

  // 创建新的聊天历史
  const createNewChatHistory = async () => {
    if (!isAuthenticated) return null;

    try {
      setLoading(true);
      const newChatHistory = await createChatHistory({
        title: `与AI助手的对话 - ${new Date().toLocaleString()}`,
        userId: user?.userId,
      });

      if (newChatHistory && newChatHistory.id) {
        dispatch(updateCurrentChat(newChatHistory));
        console.log('已创建新的聊天历史ID:', newChatHistory);
        return newChatHistory;
      }

      throw new Error('创建聊天历史失败：返回数据不完整');
    } catch (error) {
      console.error('创建新的聊天历史失败:', error);
      message.error('创建新的聊天历史失败');
      return null;
    } finally {
      setLoading(false);
    }
  };

  const handleJoinRoom = async () => {
    // 验证登录状态并尝试刷新
    if (isAuthenticated) {
      try {
        // 刷新用户信息，确保token有效
        await refreshUserInfo();
      } catch (error) {
        console.error('刷新用户信息失败:', error);
      }
    }

    // 再次检查是否已登录
    if (!isAuthenticated) {
      // 未登录，显示登录模态框
      setLoginVisible(true);
      return;
    }
    let newChat;
    // 检查是否需要创建新的聊天历史
    if (!currentChatHistoryId) {
      console.log('没有聊天历史ID，正在创建新的聊天历史...');
      newChat = await createNewChatHistory();
      if (!newChat) {
        message.error('无法创建聊天历史，请稍后再试');
        return;
      }
      setTimeout(() => {
        sidebarEvents.refreshAll();
      }, 500);
    } else {
      console.log('使用现有的聊天历史ID:', currentChatHistoryId);
    }
    const finalRoomId = newChat?.roomId || roomId || '';

    // 确保有有效的房间ID
    if (!finalRoomId) {
      message.error('房间ID无效，无法加入房间');
      return;
    }

    // 已登录，加入房间
    if (!joining) {
      await dispatchJoin(
        {
          roomId: finalRoomId,
          username, // 使用有效的用户名
          publishAudio: true,
        },
        false
      );
    }
  };

  // 登录成功后回调
  const handleLoginSuccess = () => {
    // 登录成功后自动加入房间
    handleJoinRoom();
  };

  return (
    <div className={`${style.wrapper} ${Utils.isMobile() ? style.mobile : ''}`}>
      <AvatarCard className={`${style.avatar} ${Utils.isMobile() ? style.mobile : ''}`} />
      <div className={style.title}>AI 语音助手</div>
      <AntechamberConversation className={style.conversation} />

      <InvokeButton onClick={handleJoinRoom} loading={joining || loading} className={style['invoke-btn']} />

      {/* 登录模态框 */}
      <LoginModal visible={loginVisible} onCancel={() => setLoginVisible(false)} onSuccess={handleLoginSuccess} />
    </div>
  );
}

export default Antechamber;
